package com.ktjy.ktmall.servlet;

import com.alibaba.fastjson.JSONArray;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.entity.GoodsItem;
import com.ktjy.ktmall.entity.Page;
import com.ktjy.ktmall.service.GoodsItemService;
import com.ktjy.ktmall.service.impl.GoodsItemServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @auth wzy
 * @date 2024/10/24 15:40
 */
@WebServlet(name = "GoodsItemServlet", urlPatterns = "/uni/home/goods/guessLike")
public class GoodsItemServlet extends HttpServlet {

    GoodsItemService service = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
        service = new GoodsItemServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        String opr = request.getParameter("opr");
        AjaxResult result = null;
        if ("list".equals(opr)) {
            // 3、接收从小程序传递过来的当前页码和每页显示的数据行数
            Integer currPageNo = 1; // 当前页码
            if (request.getParameter("currPageNo") != null) {
                currPageNo = Integer.valueOf(request.getParameter("currPageNo"));
            }
            Integer pageSize = 6; // 每页显示的数据行数
            if (request.getParameter("pageSize") != null) {
                pageSize = Integer.valueOf(request.getParameter("pageSize"));
            }
            // 4、调用 serivce 中查询总记录数的方法
            int count = service.getCount();
            // 5、调用 service 中查询商品的分页列表数据
            List<GoodsItem> list = service.getGoodsListPage(currPageNo, pageSize);
            // 6、封装 Page 对象
            Page page = new Page();
            page.setCurrPageNo(currPageNo);
            page.setPageSize(pageSize);
            page.setTotalCount(count);
            page.setList(list); // 将查询到的商品分页列表数据进行赋值
            result = AjaxResult.success("猜你喜欢的商品列表加载成功!", page);
        }
        // 将 result 对象转换成 JSON 字符串再响应到小程序端
        out.print(JSONArray.toJSONString(result));
        out.flush();
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
